package com.itkm.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
@Controller
public class RouterController {

    @GetMapping("/movie/{type}/{path}")
    public String showMovie(@PathVariable String type,
                            @PathVariable String path) {
        return "movie/" + type + "/" + path;
    }

    @GetMapping("/userLogin")
    public String showUserLogin() {
        return "/auth/login";
    }

    @GetMapping("/user/session")
    @ResponseBody
    public List<String> showUserSession(HttpSession session) {
        List<String> result = new ArrayList<>();
        Enumeration<String> attributeNames = session.getAttributeNames();
        while (attributeNames.hasMoreElements()) {
            String element = attributeNames.nextElement();
            SecurityContextImpl attribute = (SecurityContextImpl) session.getAttribute(element);
            UserDetails userDetails = (UserDetails) attribute.getAuthentication().getPrincipal();
            Stream.of(element, attribute, userDetails, userDetails.getUsername())
                    .map(String::valueOf)
                    .peek(result::add).forEach(log::info);
        }
        return result;
    }

    @GetMapping("/user/context")
    @ResponseBody
    public List<String> showUserContext() {
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        return Stream.of(context, userDetails, userDetails.getUsername())
                .map(String::valueOf)
                .peek(log::info).collect(Collectors.toList());
    }
}
